/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import React, { useCallback } from 'react';
import { Modal, Form, Button } from 'antd';
import { useReactive } from 'ahooks';

import Date from '../Date';
import SeekBar from '../SeekBar';
import DateCustom from '../DateCustom';
import UploadModel from '../UploadModel';

import { IBlockDataType } from '@/lib/custom-extension';
import { ElementDype } from '@/lib/dataType';
import { useEffect } from 'react';
import { useMemo } from 'react';
import { useModal } from '@/utils';
import { connect } from 'dva';
import { Action } from 'redux';

export type ICompositeComponent = {
  /** 对话框是否可见 */
  visible?: boolean;
  // 积木的id
  id?: string;
  /** 点击确定回调 */
  onOk?: (e: string) => void;
  /** 点击模态框右上角叉、取消按钮、Props.maskClosable 值为 true 时的遮罩层或键盘按下 Esc 时的回调 */
  onCancel?: () => void;
  /** 组件内容 */
  value?: string | number;
  /** 数据类型 */
  dataType?: IBlockDataType;
  dispatch?: (action: Action) => void;
  editGlobal?: any;
};

interface State {
  value: string | number | undefined;
  visible: boolean | undefined;
  fileName: string;
  fileUuid: string;
}

// 这个组件是个扩展的组件
// 方便直接更多的业务逻辑是在这里进行处理 外部 只传类型
const CompositeComponent: React.FC<ICompositeComponent> = (props) => {
  const [form] = Form.useForm();

  const { set: setGlobalState } = useModal(props.dispatch, 'editGlobal');

  const state = useReactive<State>({
    value: '',
    visible: false,
    fileName: '',
    fileUuid: '',
  });

  useEffect(() => {
    state.visible = props.visible;
    if (props.value && props.visible) {
      state.value = props.value;
    }
  }, [props.value, props.visible]);

  const hideTooltip = useCallback(() => {
    setTimeout(() => {
      const tooltipDoms = document.querySelectorAll('.formatter');
      tooltipDoms.forEach((d) => {
        const dom = d?.parentElement?.parentElement?.parentElement as HTMLDivElement;
        if (dom) {
          dom.style = `left: -10000px;top: -868px;transform-origin: 50% 52.3125px;pointer-events: none;`;
        }
      });
    }, 200);
  }, []);

  // 渲染组件
  const Component = useMemo(() => {
    switch (props.dataType?.elementType) {
      case ElementDype.RGB:
      case ElementDype.SEEKBAR: {
        return (
          <SeekBar
            value={Number(state.value)}
            dataType={props.dataType}
            onChange={(val: number) => (state.value = val)}
            visible
            colorSlider={props.dataType?.elementType === ElementDype.RGB}
          />
        );
      }
      case ElementDype.DATE: {
        return (
          <Date form={form} value={props.value as string} format={props.dataType?.value || ''} />
        );
      }
      case ElementDype.DATE_CUSTOM: {
        return (
          <DateCustom
            format={props.dataType?.value || ''}
            value={String(state.value)}
            onChange={(val) => (state.value = val)}
          />
        );
      }
      case ElementDype.MEDIA: {
        return (
          <UploadModel
            value={props.value as string}
            onChange={(fileInfo) => {
              state.fileName = fileInfo.fileName;
              state.fileUuid = fileInfo.fileUuid;
              // set(fileInfo.fileName, fileInfo.fileUuid);
              const { fileMap } = props.editGlobal;
              const map = new Map(fileMap);
              // map.set(fileInfo.fileName, fileInfo.fileUuid);
              map.set(props.id, fileInfo.fileUuid);
              setGlobalState('fileMap', map);
            }}
          />
        );
      }
      default: {
        return null;
      }
    }
  }, [props.dataType, state.visible, form, state.value, props.editGlobal]);

  const handleOk = () => {
    switch (props.dataType?.elementType) {
      case ElementDype.RGB:
      case ElementDype.SEEKBAR: {
        props.onOk?.(String(state.value));
        hideTooltip();
        break;
      }
      case ElementDype.DATE: {
        try {
          const format = props.dataType?.value || '';
          const { date, time } = form.getFieldsValue();
          const valList = [];

          if (date) {
            valList.push(date.format(format.split(' ')[0]));
          }

          if (time) {
            valList.push(time.format(format.split(' ')[1] || format.split(' ')[0]));
          }

          props.onOk?.(valList.join(' ') || '');

          // 重置
          setTimeout(() => {
            form?.resetFields();
          }, 100);
        } catch (error) {
          console.log('🚀 ~ file: index.tsx ~ line 46 ~ onFinish ~ error', error);
        }
        break;
      }
      case ElementDype.DATE_CUSTOM: {
        props.onOk?.(String(state.value));
        break;
      }
      case ElementDype.MEDIA: {
        props.onOk?.(String(state.fileName));
        break;
      }
      default: {
        break;
      }
    }
  };

  const handleCancel = () => {
    hideTooltip();
    props.onCancel?.();
  };

  useEffect(() => {
    if (!props.visible) {
      state.fileName = '';
      state.fileUuid = '';
      state.value = '';
      state.visible = false;
    }
  }, [props.visible]);

  return (
    <Modal
      title={null}
      width="45%"
      closable={false}
      visible={props.visible}
      // onCancel={props.onCancel}
      footer={
        <div>
          <Button onClick={handleCancel}>取消</Button>
          <Button type="primary" onClick={handleOk}>
            确定
          </Button>
        </div>
      }
    >
      {Component}
    </Modal>
  );
};
const mapStateToProps = (state: any) => ({
  editGlobal: state.editGlobal,
});
export default connect(mapStateToProps)(CompositeComponent);
